package com.ly.blog_data.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.blog_common.constant.Constant;
import com.ly.blog_common.security.SecurityUtils;
import com.ly.blog_common.utils.PageUtils;
import com.ly.blog_common.utils.Query;
import com.ly.blog_data.dao.DataResultDao;
import com.ly.blog_data.dao.DataTaskDao;
import com.ly.blog_data.entity.*;
import com.ly.blog_data.parse.MsgList;
import com.ly.blog_data.service.DataTaskService;
import com.ly.blog_data.service.HtmlService;
import com.ly.blog_data.utils.HtmlInfoExplainUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service("dataTaskService")
public class DataTaskServiceImpl extends ServiceImpl<DataTaskDao, DataTaskEntity> implements DataTaskService {

    @Autowired
    private HtmlService htmlService;

    @Autowired
    private DataResultDao dataResultDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper queryWrapper = new QueryWrapper<DataTaskEntity>();
        String userId = SecurityUtils.getUserId();
        if(!String.valueOf(Constant.SUPER_ADMIN).equals(userId)){
            queryWrapper.eq("create_by",userId);
        }
        IPage<DataTaskEntity> page = this.page(
                new Query<DataTaskEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public boolean exec(Integer id) {
        DataTaskEntity taskEntity = this.getById(id);

        ContentRuleEntity contentRuleEntity = new ContentRuleEntity();
        CatalogueRuleEntity catalogueRuleEntity = new CatalogueRuleEntity();
        changeRule2Obj(taskEntity,contentRuleEntity,catalogueRuleEntity);

        List<CatalogueEntity> catalogueEntities = htmlService.catchData(taskEntity.getCatalogueUrl(), catalogueRuleEntity, contentRuleEntity);

        //记录执行情况
        catalogueEntities.forEach(item ->{
            DataResultEntity dataResultEntity = new DataResultEntity();

            dataResultEntity.setTaskId(id);
            dataResultEntity.setExeUrl(item.getUrl());
            dataResultEntity.setTitle(item.getCatalogueName());
            dataResultEntity.setState(null == item.getContent()?0:1);
            dataResultEntity.setContent(item.getContent());
            dataResultEntity.setCreateTime(new Date());
            dataResultEntity.setCreateBy(SecurityUtils.getUserId());
            dataResultEntity.setLastUpdateTime(new Date());
            dataResultEntity.setLastUpdateBy(SecurityUtils.getUserId());

            dataResultDao.insert(dataResultEntity);
            log.info("【插入结果集】 --- 成功---url:{}",item.getUrl());
        });

        return true;

    }

    /**
     * 抓换规则到对象中
     * @param taskEntity
     * @param contentRuleEntity
     * @param catalogueRuleEntity
     */
    private void changeRule2Obj(DataTaskEntity taskEntity, ContentRuleEntity contentRuleEntity, CatalogueRuleEntity catalogueRuleEntity) {

        //转换规则
        JSONObject catalogueRuleJson = JSONObject.parseObject(taskEntity.getCatalogueRule());
        catalogueRuleEntity.setAreaPreList(String.valueOf(catalogueRuleJson.get("areaPreList")).split(","));
        catalogueRuleEntity.setAreaPostList(String.valueOf(catalogueRuleJson.get("areaPostList")).split(","));

        catalogueRuleEntity.setDataPre(String.valueOf(catalogueRuleJson.get("dataPre")));
        catalogueRuleEntity.setDataCenter(String.valueOf(catalogueRuleJson.get("dataCenter")));
        catalogueRuleEntity.setDataPost(String.valueOf(catalogueRuleJson.get("dataPost")));


        JSONObject contentRuleJson = JSONObject.parseObject(taskEntity.getContentRule());
        contentRuleEntity.setAreaPreList(String.valueOf(contentRuleJson.get("areaPreList")).split(","));
        contentRuleEntity.setAreaPostList(String.valueOf(contentRuleJson.get("areaPostList")).split(","));

        //自定替换键值
        Map<String,String> replaceCondition = new HashMap<>();
        String[] replaceConditionArray = String.valueOf(contentRuleJson.get("replaceCondition")).split(",");
        Arrays.asList(replaceConditionArray).forEach(item ->{
            if(item.contains("-")){
                String[] strings = item.split("-");
                replaceCondition.put(strings[0],strings.length == 1?"":strings[1]);
            }
        });
        contentRuleEntity.setReplaceCondition(replaceCondition);
    }

    @Override
    public String parseHtml(String url) {
        String htmlContent = HtmlInfoExplainUtils.getHtmlContent(url,false);
        return htmlContent;
    }

    @Override
    public MsgList<String> check(DataTaskEntity taskEntity) {
        ContentRuleEntity contentRuleEntity = new ContentRuleEntity();
        CatalogueRuleEntity catalogueRuleEntity = new CatalogueRuleEntity();
        changeRule2Obj(taskEntity,contentRuleEntity,catalogueRuleEntity);

        return htmlService.checkData(taskEntity.getCatalogueUrl(), catalogueRuleEntity, contentRuleEntity);

    }
}